package com.cskaoyan.controller;


import com.cskaoyan.bean.baseresultVO.AdminInfoBean;
import com.cskaoyan.bean.baseresultVO.BaseRespVo;
import com.cskaoyan.bean.baseresultVO.InfoData;
import com.cskaoyan.bean.baseresultVO.LoginUserData;
import com.cskaoyan.bean.domain.*;
import com.cskaoyan.mapper.AuthMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.shiro.MallToken;
import com.cskaoyan.utils.Md5Util;
import com.cskaoyan.utils.MyUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 整合shiro框架
 */
@RestController
@RequestMapping("admin/auth")
public class AuthController {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    AuthMapper authMapper;

    /**
     * 1.管理员密码采用md5加密，登录前先生成md5再去数据库进行比对
     */
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map, HttpServletRequest request) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String passwordWithMd5 = null;
        try {
            passwordWithMd5 = Md5Util.getMd5AdDefaultSalt(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Subject subject = SecurityUtils.getSubject();
        //UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username, passwordWithMd5);
        MallToken authenticationToken = new MallToken(username, passwordWithMd5, "admin");
        subject.login(authenticationToken);
        /**
         * 获得认证状态
         * boolean authenticated = subject.isAuthenticated();
         *获得用户信息
         *Object primaryPrincipal = subject.getPrincipals().getPrimaryPrincipal();
         */
        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        /**
         * 从session中获取对象
         */
        Admin admin = (Admin) subject.getPrincipals().getPrimaryPrincipal();

        adminInfo.setAvatar(admin.getAvatar());
        adminInfo.setNickName(admin.getUsername());
        loginUserData.setAdminInfo(adminInfo);
        loginUserData.setToken((String) subject.getSession().getId());
        //备用
        //request.getServletContext().setAttribute("username",username);
        //request.getSession().setAttribute("username",username);
        return BaseRespVo.ok(loginUserData);

    }

//    @RequestMapping("info")
//    public BaseRespVo info(String token) {
//        Subject subject = SecurityUtils.getSubject();
//        Serializable id = subject.getSession().getId();
//        Admin admin = (Admin) subject.getPrincipals().getPrimaryPrincipal();
//        InfoData infoData = new InfoData();
//        infoData.setName(admin.getUsername());
//
//        //根据primaryPrincipal做查询
//        infoData.setAvatar(admin.getAvatar());
//        ArrayList<String> roles = new ArrayList<>();
//        roles.add("超级管理员");
//        infoData.setRoles(roles);
//        ArrayList<String> perms = new ArrayList<>();
//        perms.add("*");
//        infoData.setPerms(perms);
//
//
//        return BaseRespVo.ok(infoData);
//    }


    /**
     * @Author: Yr
     * @Description: 处理admin/auth/info请求 前端会根据此返回数据显示相应的模块
     */
    @RequestMapping("info")
    public BaseRespVo info(String token) {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();

        //从数据库获取permissionApiList
        List<String> permissionApiList = new ArrayList<>();
        if (admin.getId() == 1) {
            //超级管理员permissionApiList为*
            permissionApiList.add("*");
        } else {
            PermissionExample permissionExample = new PermissionExample();
            permissionExample.createCriteria().andRoleIdIn(MyUtils.convertIntArrayToList(admin.getRoleIds()));
            List<Permission> permissions = permissionMapper.selectByExample(permissionExample);
            ArrayList<String> permissionNameList = new ArrayList<>();
            for (Permission permission : permissions) {
                permissionNameList.add(permission.getPermission());
            }
            permissionApiList = authMapper.selectApiByNames(permissionNameList);
        }
        //从数据库获取roleNameList
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria().andIdIn((MyUtils.convertIntArrayToList(admin.getRoleIds())));
        List<Role> roles = roleMapper.selectByExample(roleExample);
        ArrayList<String> roleNameList = new ArrayList<>();
        for (Role role : roles) {
            roleNameList.add(role.getName());
        }


        //封装返回数据
        InfoData infoData = new InfoData();
        infoData.setName(admin.getUsername());
        infoData.setAvatar(admin.getAvatar());
        infoData.setRoles(roleNameList);
        infoData.setPerms(permissionApiList);
        return BaseRespVo.ok(infoData);
    }


    /**
     * 注销这里暂时没写好
     *
     * @return
     */
    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok(null);
    }
}
